package posti.test.swf.dao.hibernate;

import java.io.Serializable;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import posti.test.swf.dao.GenericDAO;
import posti.test.swf.dao.Reference;
import posti.test.swf.dao.ReferenceImpl;

public class HibernateGenericDAO implements GenericDAO {
	private SessionFactory sessionFactory;

	public HibernateGenericDAO(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	protected Session getCurrentSession() {
		return sessionFactory.getCurrentSession();
	}

	/* (non-Javadoc)
	 * @see posti.test.swf.dao.hibernate.GenericDAO#load(posti.test.swf.dao.Reference)
	 */
	public Object load(Reference reference) throws HibernateException {
		return this.getCurrentSession().get(reference.type(), reference.id());
	}
	/* (non-Javadoc)
	 * @see posti.test.swf.dao.hibernate.GenericDAO#get(posti.test.swf.dao.Reference)
	 */
	public Object get(Reference reference) throws HibernateException {
		return this.getCurrentSession().load(reference.type(), reference.id());
	}
	/* (non-Javadoc)
	 * @see posti.test.swf.dao.hibernate.GenericDAO#save(java.lang.Object)
	 */
	public Serializable save(Object arg0) throws HibernateException {
		return this.getCurrentSession().save(arg0);
	}
	/* (non-Javadoc)
	 * @see posti.test.swf.dao.hibernate.GenericDAO#saveOrUpdate(java.lang.Object)
	 */
	public Object saveOrUpdate(Object arg0) throws HibernateException {
		this.getCurrentSession().saveOrUpdate(arg0);
		return arg0;
	}
	/* (non-Javadoc)
	 * @see posti.test.swf.dao.hibernate.GenericDAO#update(java.lang.Object)
	 */
	public Object update(Object arg0) throws HibernateException {
		this.getCurrentSession().update(arg0);
		return arg0;
	}

	/* (non-Javadoc)
	 * @see posti.test.swf.dao.hibernate.GenericDAO#delete(java.lang.Object)
	 */
	public void delete(Object object) throws HibernateException {
		this.getCurrentSession().delete(object);
	}
	
	/* (non-Javadoc)
	 * @see posti.test.swf.dao.hibernate.GenericDAO#refresh(java.lang.Object)
	 */
	public Object refresh(Object object) {
		this.getCurrentSession().refresh(object);
		return object;
	}

	public Reference reference(Object object) {
		return new ReferenceImpl(object.getClass(), this.getCurrentSession().getIdentifier(object));
	}
}
